package api;

import dao.Image;
import dao.ImageDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ImageServlet extends HttpServlet {
    /**
     * 查看图片属性，可以查看所有与指定
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200); // 状态码
        // 把hello字符串放入http响应的body中
        resp.getWriter().write("hello world!");
    }

    /**
     * 上传图片
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取图片属性信息 存入数据库
        //  1.  需要创建一个 factory 对象 和upload对象 获取图片属性
        FileItemFactory factory =  new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 2.  通过upload对象进一步解析请求 （解析HTTP请求中body内容）
        //  FileItem 就代表一个上传的文件对象
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // 解析出错
            e.printStackTrace();
            // 报出具体错误
            resp.setContentType("application/json; charset=utf-8");
            resp.getWriter().write("{\"ok\":false, \"reason\":\"请求解析失败\"}");
            return;
        }

        // 把FileItem中的属性提取出来，转换Image对象
        FileItem  fileItem = items.get(0);
        Image image = new Image();
        image.setImageName(fileItem.getName());
        image.setSize((int) fileItem.getSize());
        // 手动获取当前日期，并转化格式化时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        image.setUploadTime(simpleDateFormat.format(new Date()));
        image.setContentType(fileItem.getContentType());
        // 构造路径
        image.setPath("./image/"+ System.currentTimeMillis() + "_" + image.getImageName());
        // TODO 暂时放这儿
        image.setMd5("1234");
        // 存到数据库
        ImageDao imageDao = new ImageDao();
        imageDao.insert(image);

        // 获取图片内容信息 写入磁盘文件
        File file = new File(image.getPath());
        try {
            fileItem.write(file);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setContentType("application/json; charset=utf-8");
            resp.getWriter().write("{\"ok\":false, \"reason\":\"写入磁盘文件失败\"}");
            return;
        }
        // 给客户端返回结果数据
        resp.setContentType("application/json; charset=utf-8");
        resp.getWriter().write("{\"ok\": true }");
    }

    /**
     * 删除指定图片
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
